import type { Expression, StringLiteral, ts } from 'ts-morph'
import { SyntaxKind } from 'ts-morph'

export function getObjectProperty(element: Expression, propertyName: string): Expression<ts.Expression> | null {
  if (!element.isKind(SyntaxKind.ObjectLiteralExpression))
    return null

  const property = element.getProperty(propertyName)
  if (!property?.isKind(SyntaxKind.PropertyAssignment))
    return null

  const value = property.getInitializer()

  return value || null
}

export function getStringProperty(element: Expression, propertyName: string): StringLiteral | null {
  const value = getObjectProperty(element, propertyName)
  if (!value?.isKind(SyntaxKind.StringLiteral))
    return null

  return value
}

export function updateStringProperty(element: Expression, propertyName: string, newValue: string): void {
  const value = getStringProperty(element, propertyName)
  if (!value)
    return

  value.replaceWithText(`'${newValue}'`)
}
